package com.rcloud.server.sealtalk.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.github.binarywang.java.emoji.EmojiConverter;
import com.rcloud.server.sealtalk.domain.UserAdvertisement;
import com.rcloud.server.sealtalk.util.ImageHandleUtils;
import com.rcloud.server.sealtalk.util.MyWebSocketClient;
import com.rcloud.server.sealtalk.util.WebSocketClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Component
public class MiniWebSocketService {

    private List<MyWebSocketClient> joinArray = new ArrayList<>();

    @Resource
    private WebSocketClient socketClient;

    /**
     * 用户加入的的定时任务
     */
    public void userJoinTask(UserAdvertisement advertisement) {
        //业务处理
        DateTime date = DateUtil.date();
        log.info("执行websocket的用户加入的定时任务---------------------开始" + date);
        try {
            EmojiConverter emojiConverter = EmojiConverter.getInstance();
            if (advertisement.getContent() == null) {
                advertisement.setContent(advertisement.getTitle());
            }
            if ("聆听小助手".equals(advertisement.getUserNickname()) || "通知小助手".equals(advertisement.getUserNickname())) {
                Random random = new Random();
                advertisement.setUserNickname("聆听科技" + random.nextInt(9999));
            }
            MyWebSocketClient myWebSocketClient;
            log.info("连接池中的连接数" + joinArray.size());
            if (joinArray.size() < 301) {
                myWebSocketClient = socketClient.joinWebSocket(advertisement.getUserNickname());
                joinArray.add(myWebSocketClient);
            } else {
                Random random = new Random();
                int r = random.nextInt(joinArray.size() - 1);
                myWebSocketClient = joinArray.get(r);
            }
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(advertisement.getContent());
            String s = subRangeString(m.replaceAll(""), "[", "]");
            //转换emoji的表情
            String content = emojiConverter.toHtml(emojiConverter.toUnicode(s));
            String msg = ("[CHAT][" + new Date().getTime() + "]" + "[" + advertisement.getUserNickname() + "][" + advertisement.getUserAvatar() + "] - " + content);
            myWebSocketClient.sendMessage(msg);
            //循环发送图片信息
            if (advertisement.getImageUrl() != null && !"".equals(advertisement.getImageUrl())) {
                String[] imageArray = advertisement.getImageUrl().split(",");
                for (String url : imageArray) {
                    String _img = "<img src='" + url + "'>";
                    String msg2 = ("[CHAT][" + new Date().getTime() + "]" + "[" + advertisement.getUserNickname() + "][" + advertisement.getUserAvatar() + "] - " + _img);
                    myWebSocketClient.sendMessage(msg2);
                }
            }
        } catch (Exception e) {
            log.error("这里是websocket发送消息失败" + e);
        }
        log.info("执行websocket用户加入的方法---------------------结束" + date.getTime());
    }

    private static String subRangeString(String body, String str1, String str2) {
        while (true) {
            int index1 = body.indexOf(str1);
            if (index1 != -1) {
                int index2 = body.indexOf(str2, index1);
                if (index2 != -1) {
                    String str3 = body.substring(0, index1) + body.substring(index2 + str2.length(), body.length());
                    body = str3;
                } else {
                    return body;
                }
            } else {
                return body;
            }
        }
    }

}
